#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
	if(argc == 2)
	{
		string line;
		vector<string> filelines;
		filelines.reserve(2110);
		
		// put each line of the file in a vector
		{
			ifstream oldfile(argv[1]);

			while(getline(oldfile, line))
			{
				line.append("\n");
				filelines.push_back(line);
			}
		}

		// truncate the file
		ofstream newfile(argv[1], std::ios::trunc);

		if(strstr(argv[1], ".cpp") != NULL)
		{
			// Find the unistd include line
			vector<string>::iterator iter = find(filelines.begin(), filelines.end(), "#include <unistd.h>\n");
			if(iter != filelines.end())
			{
				// if the line before it is the erroneous non-std definition of istream
				// delete it
				if(*(iter - 1) == "class istream;\n")
				{
					iter = filelines.erase(iter - 1);
				}
				// delete the unistd include
				filelines.erase(iter);
			}
		}

		// write the amended vector to the file
		copy(filelines.begin(), filelines.end(), ostream_iterator<string>(newfile));

		return 0;
	}
	else
	{
		std::cout << "Expected a file name as an argument\n";
	}
	return 1;
}
